Tutorial Part IV - Movement - Solution Exercise 1

Exercise 4

Exercise 4.1

This is recap from Course2. Please plot the animal relocations in two different colours for column ‘daytime’, using the data.frame and one of the options with {ggplot2}, {ggpmap}, {leaflet} or {tmap}. Use the processed file of fox Q (tag5334_gps_proc) and do it in a separate script. Save your script as Course4_Exercise1_*yourname*.R.

Hint: Remember to load the relevant libraries. Note that you might want to plot the locations in the correct spatial dimensions by projecting it using the functions st_as_sf() and st_transform().

  1. Load the processed data file
library(here)
library(sf)
animal <- readRDS(file = here("output", "data-proc", "tag5334_gps_proc.Rds")) 

## transform into spatial simple feature sf object
mydf_sf <- st_as_sf(x = animal, ## data.frame(animal) -> bei mir geht's auch ohne data.frame()
                    coords = c("longitude", "latitude"),
                    crs = 4326,
                    sf_column_name = "geometry" )
## and project
mydf_sf_trans <- st_transform(mydf_sf, 5631)  ## EPSG-code Pulkovo


  1. Plot the data

Base R

A quick plot from the simple data.frame

## latitude is y-Axis, longitude = x-axis in cartesian coordinate system
plot(animal$latitude ~ animal$longitude,
     pch = ".",
     col = as.numeric(animal$daytime) + 1) ## + 1 because color 0 is transparent


A quick plot of the movement path, using only the first 50 observations:

plot(animal$latitude[1:50] ~ animal$longitude[1:50], type= 'l') 


The problem: all of the observations are not projected but use the Cartesian coordinates (i.e. in a default, rectangular 2-D projection).


{ggplot2}

The first approach might be to plot the x and y coordinates with using geom_point():

library(ggplot2)

baseplot_df <- 
  ggplot(data = animal, 
         aes(x = longitude,
             y = latitude,
             color = daytime)) +
    geom_point(size = 0.01, alpha = 0.5) +  
    labs(x = "Longitude", y = "Latitude",
         title = "Telemetry data") +
    theme_bw(base_size = 16)

baseplot_df


Note that the baseplot_df uses x and y coordinates but not the projection (i.e. the distance between points changes when changing the aspect ratio of the plot) as it uses a Cartesian coordinate system as in the base plot.

As we are dealing with spatial data, it is better to use the projected sf object with the dedicated geom_sf() layer for {ggplot2}:

baseplot_sf <- 
  ggplot(data = mydf_sf_trans, 
         aes(color = daytime)) +
    geom_sf(size = 0.01, alpha = 0.5) +  
    labs(x = "Longitude", y = "Latitude",
         title = "Telemetry data") +
    theme_bw(base_size = 16)

baseplot_sf

Get more inspiration here: https://github.com/Z3tt/TidyTuesday/blob/master/R/2020_26_CaribouLocations.Rmd


{ggmap}

We can also add a background using the {ggmap} package. Check the cheatsheet for a quick start to {ggmap}: https://www.nceas.ucsb.edu/sites/default/files/2020-04/ggmapCheatsheet.pdf

library(ggmap)

## define a bounding box for the plot
b <- c(13.460, 52.485, 13.490, 52.500) ## make large enough to plot all data!

my_tiles <- get_map(location = b, maptype = "terrain", source = "osm", zoom = 15)

ggmap(my_tiles) + 
  geom_point(aes(x = longitude, y = latitude), 
             data = data.frame(animal), 
             colour = as.numeric(animal$daytime) + 6, 
             size = 0.05) + 
  labs(x = "Latitude", y = "Longitude", title = "Telemetry locations")



{leaflet}

A nice interactive plot can be created with {leaflet}. The first location of the track is marked:

library(leaflet)

# get first location of track
base_wgs84_x <- animal$longitude[1]
base_wgs84_y <- animal$latitude[1]

m_leaf <- leaflet(animal) %>% 
  addTiles() %>%
  addMarkers(lng = base_wgs84_x, lat = base_wgs84_y, 
             popup = "Start") %>%
  addPopups(base_wgs84_x, base_wgs84_y, "Starting point",
            options = popupOptions(closeButton = TRUE)) %>%
  addCircles(lng = ~longitude, lat = ~latitude, ~5,
             stroke = TRUE,
             color = "white",
             weight = 1,
             fill = TRUE, 
             fillColor = "blue",
             fillOpacity = 0.3) 

m_leaf


{leaflet} maps are great for interactive usage but bad for export -> create maps with {ggplot2} and {ggmap} or {tmap} instead!


{tmap}

Finally a static and an interactive map via {tmap}:

library(tmap)

tmap_mode(mode = "plot")

tm_shape(shp = mydf_sf_trans) + 
  tm_dots(size = 0.01, 
          col = "daytime",  
          alpha = 0.5) 

tmap_mode(mode = "view")

tm_shape(shp = mydf_sf_trans) + 
  tm_dots(size = 0.01, 
          col = "daytime",  
          alpha = 0.5) 

END


Session Info
Sys.time()
## [1] "2022-03-07 10:48:02 CET"
sessionInfo()
## R version 4.1.2 (2021-11-01)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19043)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252   
## [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                   
## [5] LC_TIME=C                      
## system code page: 65001
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] tmap_3.3-2      leaflet_2.0.4.1 ggmap_3.0.0     ggplot2_3.3.5  
## [5] sf_1.0-5        here_1.0.1     
## 
## loaded via a namespace (and not attached):
##  [1] bitops_1.0-7            RColorBrewer_1.1-2      httr_1.4.2             
##  [4] rprojroot_2.0.2         tools_4.1.2             bslib_0.3.1            
##  [7] utf8_1.2.2              R6_2.5.1                KernSmooth_2.23-20     
## [10] DBI_1.1.2               colorspace_2.0-2        raster_3.5-11          
## [13] withr_2.4.3             sp_1.4-6                tidyselect_1.1.1       
## [16] curl_4.3.2              compiler_4.1.2          leafem_0.1.6           
## [19] textshaping_0.3.6       isoband_0.2.5           labeling_0.4.2         
## [22] bookdown_0.24           sass_0.4.0              scales_1.1.1           
## [25] classInt_0.4-3          proxy_0.4-26            systemfonts_1.0.3      
## [28] stringr_1.4.0           digest_0.6.29           rmarkdown_2.11         
## [31] base64enc_0.1-3         dichromat_2.0-0         jpeg_0.1-9             
## [34] pkgconfig_2.0.3         htmltools_0.5.2         fastmap_1.1.0          
## [37] highr_0.9               htmlwidgets_1.5.4       rlang_0.4.12           
## [40] jquerylib_0.1.4         farver_2.1.0            generics_0.1.1         
## [43] jsonlite_1.7.2          crosstalk_1.2.0         dplyr_1.0.7            
## [46] magrittr_2.0.1          s2_1.0.7                Rcpp_1.0.7             
## [49] munsell_0.5.0           fansi_0.5.0             abind_1.4-5            
## [52] lifecycle_1.0.1         terra_1.4-22            stringi_1.7.5          
## [55] leafsync_0.1.0          yaml_2.2.1              MASS_7.3-54            
## [58] tmaptools_3.1-1         plyr_1.8.6              grid_4.1.2             
## [61] parallel_4.1.2          crayon_1.4.2            lattice_0.20-45        
## [64] stars_0.5-5             knitr_1.36              pillar_1.6.4           
## [67] rjson_0.2.21            codetools_0.2-18        wk_0.6.0               
## [70] XML_3.99-0.8            glue_1.4.2              evaluate_0.14          
## [73] leaflet.providers_1.9.0 png_0.1-7               vctrs_0.3.8            
## [76] rmdformats_1.0.3        RgoogleMaps_1.4.5.3     gtable_0.3.0           
## [79] purrr_0.3.4             tidyr_1.1.4             assertthat_0.2.1       
## [82] xfun_0.27               lwgeom_0.2-8            e1071_1.7-9            
## [85] ragg_1.1.3              class_7.3-19            viridisLite_0.4.0      
## [88] tibble_3.1.6            units_0.7-2             ellipsis_0.3.2